﻿using CocoaAni.Net.WebSockets.Server;
using CocoaAni.Net.WebSockets.Server.Attributes;
using CocoaAni.Net.WebSockets.Server.Controllers;
using CocoaAni.Net.WebSockets.Server.Exceptions;
using static WebSocketServerTest.TestController;

namespace WebSocketServerTest;

[WebSocketController]
public class TestController : WebSocketController
{
    public record User(string UserName, string Password);
    public Dictionary<WebSocketContext,User> Users;

    public TestController()
    {
        Users=new Dictionary<WebSocketContext, User>();
    }
    public override async Task<object?> OnOpen(WebSocketContext context)
    {
        context.SendMessage("欢迎使用 CocoaAni.Net.Websockets.Server\n请输入用户名：");
        var userName = (await context.ReceiveMessageAsync()).ToString();
        context.SendMessage("输入密码：");
        var password = (await context.ReceiveMessageAsync()).ToString();
        var user = new User(userName, password);
        Users.Add(context, user);
        context.Dispatcher.BroadcastMessage($"用户{user.UserName} 进入聊天室!", Users.Keys, context);
        return $"欢迎进入{user.UserName}聊天室";
    }

    [DefaultMessageHandler]
    public string Chart(WebSocketContext context, [TextArg] string msg)
    {
        var user = Users[context];
        context.Dispatcher.BroadcastMessage($"{user.UserName}: {msg}", Users.Keys, context);
        return "消息发送成功！";
    }

    public override void OnClosed(WebSocketContext context)
    {
        if (Users.ContainsKey(context))
        {
            Users.Remove(context);
        }
        Console.WriteLine($"客户端：{context.ClientId} 退出了！");
    }
}